package acaai.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.mail.Session;

import org.apache.commons.validator.routines.EmailValidator;

import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.cmd.Query;

import struct.AcaaiUserServer;

import static com.googlecode.objectify.ObjectifyService.ofy;

import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

import struct.AcaaiUserFactory;
import struct.AcaaiUserPromise;

public class InvitarUsuarioServlet extends HttpServlet {
	static {
        ObjectifyService.register(AcaaiUserPromise.class);
	}
	private static final long serialVersionUID = 1L;

	/**
	 * Agrega usuarios promesa para directivos que buscan un puesto
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
			String email = req.getParameter("email");
			if(EmailValidator.getInstance().isValid(email)){
				//Revisamos si ya existe
				Query<AcaaiUserServer> existeUser = ofy().load().type(AcaaiUserServer.class).filter("email", email);
				Query<AcaaiUserPromise> existePUser = ofy().load().type(AcaaiUserPromise.class).filter("email", email);
				if((existeUser.count() + existePUser.count())>0){
					//Si ya existe lo notificamos
					resp.sendRedirect("/home?emailExists="+email);
				}else{
					//Si no, la creamos
					AcaaiUserPromise userp = new AcaaiUserPromise(email, AcaaiUserFactory.ASPIRANTE);
					ofy().save().entity(userp);
					resp.sendRedirect("/home?accountRequested="+email);
				}
				
			}else{
				resp.sendRedirect("/home?invalidEmail="+email);
			}
		}
	
}
